package com.ins.service.impl;


import com.ins.common.enums.ClassifyEnum;
import com.ins.common.exception.ServerException;
import com.ins.mapper.AppPromotionMapper;
import com.ins.model.entity.AppPromotion;
import com.ins.model.query.Query;
import com.ins.model.vo.AppPromotionVO;
import com.ins.service.AppPromotionService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.lang.Assert;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

import static com.ins.model.entity.table.AppPromotionTableDef.APP_PROMOTION;

/**
 * 推广记录 服务层实现。
 *
 * @author ins
 * @since 2024-05-14
 */
@Service
@RequiredArgsConstructor
public class AppPromotionServiceImpl extends ServiceImpl<AppPromotionMapper, AppPromotion> implements AppPromotionService {


    @Override
    public Page<AppPromotionVO> pages(Query query) {

        return mapper.paginateWithRelations(Page.of(query.getPage(), query.getLimit()), query()).map(a -> {
            AppPromotionVO vo = new AppPromotionVO();
            BeanUtil.copyProperties(a, vo);
            vo.setRemainder(countRemainder(a.getStartTime(), a.getTimes()));
            vo.setPic(a.getAif().getPic().get(0));
            vo.setName(a.getAif().getName());
            vo.setPortfolioList(a.getAif().getPortfolio());
            vo.setClassifyName(ClassifyEnum.getClassifyVal(a.getAif().getClassify().toUpperCase()));
            return vo;
        });
    }

    @Override
    public AppPromotionVO getInfo(Long id) {
        Assert.notNull(id, () -> ServerException.spe("数据不存在"));
        AppPromotion a = mapper.selectOneWithRelationsByCondition(APP_PROMOTION.ID.eq(id));
        Assert.notNull(a, () -> ServerException.spe("数据不存在"));
        AppPromotionVO vo = new AppPromotionVO();
        BeanUtil.copyProperties(a, vo);
        vo.setPic(a.getAif().getPic().get(0));
        vo.setName(a.getAif().getName());
        vo.setPortfolioList(a.getAif().getPortfolio());
        vo.setRemainder(countRemainder(a.getStartTime(), a.getTimes()));
        return vo;
    }

    /**
     * 计算剩余时间
     *
     * @param startDate 开始时间
     * @param times     购买时长
     * @return 剩余时长
     */
    private Long countRemainder(LocalDateTime startDate, Integer times) {
        LocalDateTime endDate = startDate.plusHours(times);
        LocalDateTime now = LocalDateTime.now();
        long remainder = 0L;
        if (endDate.isAfter(now)) {
            remainder = ChronoUnit.HOURS.between(now, endDate);
        }
        return remainder < 0 ? 0 : remainder;
    }
}